import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

/// 权限管理服务类
/// Permission management service class
class PermissionService {
  static final PermissionService _instance = PermissionService._internal();
  factory PermissionService() => _instance;
  PermissionService._internal();

  /// 检查并请求必要权限
  /// Check and request necessary permissions
  Future<bool> checkAndRequestPermissions() async {
    try {
      // 需要检查的权限列表
      // List of permissions to check
      List<Permission> permissions = [
        Permission.notification, // 通知权限
      ];

      // 检查权限状态
      // Check permission status
      Map<Permission, PermissionStatus> statuses = await permissions.request();
      
      // 检查是否所有权限都已授予
      // Check if all permissions are granted
      bool allGranted = statuses.values.every((status) => status.isGranted);
      
      if (!allGranted) {
        // 显示权限说明对话框
        // Show permission explanation dialog
        return await _showPermissionDialog();
      }
      
      return true;
    } catch (e) {
      debugPrint('权限检查失败: $e');
      return false;
    }
  }

  /// 显示权限申请对话框
  /// Show permission request dialog
  Future<bool> _showPermissionDialog() async {
    bool? result = await Get.dialog<bool>(
      AlertDialog(
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        title: Row(
          children: [
            Icon(
              Icons.security_rounded,
              color: Colors.orange,
              size: 28,
            ),
            const SizedBox(width: 12),
            const Text(
              '权限申请',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '为了为您提供更好的服务体验，应用需要以下权限：',
              style: TextStyle(
                fontSize: 16,
                color: Colors.black54,
                height: 1.5,
              ),
            ),
            const SizedBox(height: 16),
            _buildPermissionItem(
              icon: Icons.notifications_rounded,
              title: '通知权限',
              description: '用于推送运势提醒和重要消息',
            ),
            const SizedBox(height: 12),
            _buildPermissionItem(
              icon: Icons.wifi_rounded,
              title: '网络权限',
              description: '用于获取最新的运势数据',
            ),
            const SizedBox(height: 20),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.blue.shade200),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.info_outline_rounded,
                    color: Colors.blue.shade600,
                    size: 20,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      '我们承诺严格保护您的隐私，不会收集任何敏感信息',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.blue.shade700,
                        height: 1.4,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Get.back(result: false);
              // 退出应用
              SystemNavigator.pop();
            },
            style: TextButton.styleFrom(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            child: const Text(
              '拒绝并退出',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          ElevatedButton(
            onPressed: () async {
              Get.back(result: true);
              // 重新请求权限
              await _requestPermissionsAgain();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              elevation: 2,
            ),
            child: const Text(
              '同意授权',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
      barrierDismissible: false,
    );

    return result ?? false;
  }

  /// 构建权限项目组件
  /// Build permission item widget
  Widget _buildPermissionItem({
    required IconData icon,
    required String title,
    required String description,
  }) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.blue.shade100,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(
            icon,
            color: Colors.blue.shade600,
            size: 20,
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
              const SizedBox(height: 4),
              Text(
                description,
                style: const TextStyle(
                  fontSize: 14,
                  color: Colors.black54,
                  height: 1.3,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 重新请求权限
  /// Request permissions again
  Future<void> _requestPermissionsAgain() async {
    try {
      // 请求通知权限
      PermissionStatus notificationStatus = await Permission.notification.request();
      
      if (notificationStatus.isDenied || notificationStatus.isPermanentlyDenied) {
        // 如果权限被拒绝，显示设置引导
        await _showSettingsDialog();
      }
    } catch (e) {
      debugPrint('重新请求权限失败: $e');
    }
  }

  /// 显示设置引导对话框
  /// Show settings guide dialog
  Future<void> _showSettingsDialog() async {
    await Get.dialog(
      AlertDialog(
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        title: Row(
          children: [
            Icon(
              Icons.settings_rounded,
              color: Colors.orange,
              size: 28,
            ),
            const SizedBox(width: 12),
            const Text(
              '权限设置',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.settings_applications_rounded,
              size: 64,
              color: Colors.blue.shade300,
            ),
            const SizedBox(height: 16),
            const Text(
              '需要在系统设置中手动开启权限',
              style: TextStyle(
                fontSize: 16,
                color: Colors.black87,
                fontWeight: FontWeight.w500,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 8),
            const Text(
              '请前往 设置 > 应用管理 > 星命之境 > 权限管理\n开启通知权限',
              style: TextStyle(
                fontSize: 14,
                color: Colors.black54,
                height: 1.5,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Get.back();
              SystemNavigator.pop();
            },
            child: const Text(
              '退出应用',
              style: TextStyle(color: Colors.grey),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Get.back();
              openAppSettings();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
            ),
            child: const Text('前往设置'),
          ),
        ],
      ),
      barrierDismissible: false,
    );
  }

  /// 检查权限状态
  /// Check permission status
  Future<bool> checkPermissionStatus() async {
    try {
      PermissionStatus notificationStatus = await Permission.notification.status;
      return notificationStatus.isGranted;
    } catch (e) {
      debugPrint('检查权限状态失败: $e');
      return false;
    }
  }
}